//
//  YHComposeView.swift
//  YHWeibo
//
//  Created by 昱含 on 16/5/28.
//  Copyright © 2016年 YuHan. All rights reserved.
//

import UIKit
import SnapKit
class YHComposeView: UIView {
    
    private lazy var buttons: [YHComposeButton] = [YHComposeButton]()
    
    var target: UIViewController?
    func show(target: UIViewController) {
        self.target = target
        target.view.addSubview(self)
    }
    override init(frame: CGRect) {
        let rect = UIScreen.mainScreen().bounds
        
        super.init(frame: rect)
        setupUI()
//        backgroundColor = UIColor(white: 0.95, alpha: 1)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for (index,btn) in buttons.reverse().enumerate() {
             startAnimation(btn, index: index, offset: 350)
        }
       
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(superview)
        for (index,btn) in buttons.enumerate() {
            startAnimation(btn, index: index, offset: -350)
        }
    }
    
    private func startAnimation(btn: YHComposeButton, index: Int, offset: CGFloat){
        UIView.animateWithDuration(0.8, delay: Double(index) * 0.02, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: [], animations: {
            //修改按钮的y值
            btn.center = CGPoint(x: btn.center.x, y: btn.center.y + offset)
            }, completion: { (_) in
                if offset > 0 {
                    //移除
                    self.removeFromSuperview()
                }
        })

    }
    
    private func setupUI() {
        backgroundColor = UIColor.redColor()
        addSubview(backImageView)
        let toolbar = UIToolbar(frame: backImageView.bounds)
        addSubview(toolbar)
        addSubview(sloganView)
        sloganView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.snp_centerX)
            make.top.equalTo(self.snp_top).offset(100)
        }
        addChildButtons()
        
    }
    
    private func addChildButtons() {
        let count = composeItems.count
        let w: CGFloat = 80
        let h: CGFloat = 120
        let margin: CGFloat = (screenWidth - 3 * w)/4
        for i in 0..<count {
            let btn = YHComposeButton()
            let item = composeItems[i]
//            btn.backgroundColor = UIColor.yellowColor()
            btn.composeItem = item
            btn.addTarget(self, action: #selector(YHComposeView.btnClick(_:)), forControlEvents: .TouchUpInside)
            let row: Int = i / 3
            let col: Int = i % 3
            let x = CGFloat(col) * (w + margin) + margin
            let y = CGFloat(row) * (h + margin) + screenHight //- 350
            btn.frame = CGRect(x: x, y: y, width: w, height: h)
            self.addSubview(btn)
            buttons.append(btn)
        }
        
        
    }
    
    @objc private func btnClick(btn: YHComposeButton){
        for button in buttons {
            var scale: CGFloat = 0
            if button == btn {
                scale = 2.0
            }else{
                scale = 0.2
            }
            
            UIView.animateWithDuration(0.25, animations: {
                button.alpha = 0
                button.transform = CGAffineTransformMakeScale(scale, scale)
                }, completion: { (_) in
//                    print("OK")
            })
        }
        guard let targetName = btn.composeItem?.target else{
            return
        }
        
        let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.3))
        dispatch_after(time_t, dispatch_get_main_queue()) { 
            let type = NSClassFromString(targetName) as! UIViewController.Type
            let vc = type.init()
            let nav = UINavigationController(rootViewController: vc)
            self.target?.presentViewController(nav, animated: true, completion: { () -> Void in
                self.removeFromSuperview()
            })
        }

    }
    
    private lazy var backImageView: UIImageView = UIImageView(image: UIImage.snapCurrentWindow())
    private lazy var sloganView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    private lazy var composeItems: [YHComposeItem] = {
        var array = [YHComposeItem]()
        let path = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil)!
        let  itemArray = NSArray(contentsOfFile: path) as! [[String : AnyObject]]
        for item in itemArray{
            let composeItem = YHComposeItem(dict: item)
            array.append(composeItem)
        }
        return array
        
    }()

}
